package com.heima.comment.service.impl;

import com.heima.comment.dto.CommentSaveDto;
import com.heima.comment.entity.ApComment;
import com.heima.comment.entity.ApUser;
import com.heima.comment.feign.UserFeign;
import com.heima.comment.service.ICommentService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 发表评论
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
//        判斷內容是否 > 140字
        if (dto == null || StringUtils.isEmpty(dto.getContent()) || dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
//        判斷是否登录
        User user = AppThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
//        安全过滤 集成阿里云的文本审核
//        String text = dto.getContent();
//        boolean textResult = checkText();
//        if (!textResult) ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);

//        构建评论对象
        ApComment comment = new ApComment();
        comment.setAuthorId(user.getUserId());
//        comment.
//        构建用户名和头像
//        根据ID到用户微服务进行查询
        ResponseResult<ApUser> userById = userFeign.getUserById(user.getUserId());
        if (userById.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            ApUser apUser = userById.getData();
        }
        comment.setEntryId(dto.getArticleId());
        comment.setType(0);
        comment.setContent(dto.getContent());
        comment.setLikes(0);
        comment.setReply(0);
        comment.setFlag(0);
        comment.setCreatedTime(new Date());
//        保存评论
        mongoTemplate.save(comment);
        return ResponseResult.okResult();
    }
}
